package cn.wolfcode.trip.app.web.controller;


import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@RestController@RequestMapping("/regions")
public class RegionController {

    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ServletContext ctx;

    /**
     * 查询所有地区
     * @return
     */
    @GetMapping("")
    public Object list() {
        List<Region> list = regionService.query();
        return list;
    }

    /**
     * 查询状态为推荐的所有地区
     * @param state
     * @return List<Region>
     */
    @GetMapping("/{state}/strategies")
    public Object selectCommonStrategy(@PathVariable Integer state) {
        return regionService.selectCommend(state);
    }

    /**
     * strategyCatalogs页面,某地区下的当季推荐攻略和全部攻略
     * @param qo
     * @param resp 模版生成的HTML数据
     * @throws Exception
     */
    @GetMapping(value = "/strategies",produces = "text/html;chartset=utf-8")
    public void selectStrategyByRegionIdSendHtml(StrategyQueryObject qo, HttpServletResponse resp) throws Exception {
        //该地区下的所有攻略(分页)
        PageInfo alls = strategyService.selectCommend(qo);
        //该地区下的推荐攻略(不分页)
        qo.setState(Strategy.STATE_COMMEND);
        qo.setPageSize(0);
        PageInfo commends = strategyService.selectCommend(qo);

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
        cfg.setDirectoryForTemplateLoading(new File(ctx.getRealPath("/template")));

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("alls", alls);
        map.put("commends", commends);

        Template temp = cfg.getTemplate("strategy.ftl", "UTF-8");
        temp.process(map, resp.getWriter());

    }

    /**
     * 加载分页下的全部攻略的数据
     * @param qo
     * @return pageInfo
     */
    @GetMapping(value = "/strategies",produces = "application/json;chartset=utf-8")
    public Object selectStrategyByRegionIdSendJson(StrategyQueryObject qo){
        return strategyService.selectByRegionId(qo);
    }

}
